﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace testServerSocket
{
    class SynchronousSocketListener
    {
        public static string data = null;
        
        
        public static void StartListening()
        {
            byte[] bytes = new Byte[1024];
            
            
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPAddress ipAddress = IPAddress.Parse("10.10.0.11");
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress,29999);
            
             

            //IPEndPoint localEndPoint = new IPEndPoint("127.0.0.1", 11000);

            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {                
                listener.Bind(localEndPoint);
                listener.Listen(10);
                //while (true)
                //{
                    Console.WriteLine("Waiting for a connection...");
                    Socket handler = listener.Accept();
                    data = null;
                    //while (true)
                    //{
                        bytes = new byte[1024];
                        int byteRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, byteRec);
                    //    if(data.IndexOf("<EOF>")>-1)
                    //        break;
                    //}
                    Console.WriteLine("Text receive: {0} ",data);

                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                //}
            }
            catch(Exception ex){
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("\n Press Enter to continue ...");
            Console.Read();
        }
    }
}
